import { createRouter, createWebHistory } from 'vue-router';
import LoginVue from '../view/Login.vue';
import MainVue from '../view/main.vue';
import UserListVue from '../view/UserList.vue';
import BookLisVue from '../view/BookList.vue'
import index from '../view/index.vue'
import borrowInfoList from '../view/borrowInfoList.vue'
import permission from '../view/Permission.vue'
import registVue from '../view/regist.vue'
import borrowInfoList2 from '../view/borrowInfoList2.vue'
import borrowInfoList3 from'../view/BorrowInfoList3.vue'
import forgetPassword from '../view/forgetPassword.vue'
// import testParent from '../view/testParents.vue'
import Vue404 from "../view/404.vue"


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'testParent',
      component: LoginVue
    },
    {
      path: '/regist',
      name: 'regist',
      component: registVue
    },
    {
      path: '/404',
      component: Vue404
    },
    {
      path: '/forgetps',
      name: 'forgetps',
      component: forgetPassword
    },
    {
      path: '/main',
      name: 'MainVue',
      component: MainVue,

      children: [
        {
          path: '',
          component: index
        },
       
        {
          path: 'userList',
          component: UserListVue
        }, {
          path: 'bookList',
          component: BookLisVue
        },
        {
          path: 'borrowInfoList',
          component: borrowInfoList
        }
        ,
        {
          path: 'borrowInfoList2',
          component: borrowInfoList2
        }

        ,
        {
          path: 'borrowInfoList3',
          component: borrowInfoList3
        },

        {
          path: 'permissionList',
          component: permission
        }
      ]
    }

  ]
})
// 路由跳转前都是会经过beforeEach，而beforeEach可以通过next来控制到底去哪个路由。根据这个特性我们就可以在beforeEach中设置一些条件来控制路由的重定向

// to => route : 即将进入的目标路由对象
// from => route : 当前导航正要离开的路由
// next => function： 一定要调用该方法来 resolve这个钩子，执行效果以来 next 方法的调用参数 
// 本次是实现一个简单的登录页面跳转到多个页面的过程，跳转页面也附带了一些条件
// 1.每次登录要进行存储token
// 2.每次登录退出进行清除token
// 3.阻止修改url上hash参数进行访问后台主页，这里用到的是导航守卫beforeEach进行检测本地存储中是否有token，要是有token就能访问后台主页，没有就不能
// 只要发生了路由的跳转 必然会触发beforeEach指定的function回调函数
router.beforeEach((to, from, next) => {

  //需要检查是否登录的白名单
  const pathArr = [
    '/main',
    '/main/userList',
    '/main/bookList',
    '/main/borrowInfoList',
    '/main/borrowInfoList2',
    '/main/borrowInfoList2',
    "/main/permissionList"
  ]
  // 找to.path在不在这个pathArr数组里面,要是等于-1就是不在,不等于-1就是在
  if (pathArr.indexOf(to.path) !== -1) {
    // 要访问后台主页,需要判断是否有token
    const user = sessionStorage.getItem('user')
    if (user) {
      next()
    } else {
      next('/')
    }
  } else {
    next()
  }
})





export default router
